﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
using Tisonet.Dobrak.Domain.Models;
using Tisonet.Dobrak.Domain.Services.Downloaders;
using Tisonet.Dobrak.Domain.Services.Projections;

namespace Tisonet.Dobrak.Domain.Services.Movies
{
    public class DobrakMoviesProvider : IMoviesProvider
    {
        //ajax_den=2&
        private const string DOBRAK_WEB_URL = "http://www.kinonadobraku.cz/index.php?ajax_id=program";

        private readonly IDownloader _downloader;

        public DobrakMoviesProvider(IDownloader downloader)
        {
            _downloader = downloader;
        }

        public async Task<Movie> GetMovieAsync(string movieName)
        {
            Uri sourceWebUri = CreateSourceUri(movieName);

            Stream stream = await _downloader.DownloadAsync(sourceWebUri);

            using (stream)
            {
                Movie movie = ParseMovieFromHtmlStream(stream);

                return movie;
            }
        }

        private Uri CreateSourceUri(string movieName)
        {
            return new Uri(string.Format("{0}&ajax_den={1}", DOBRAK_WEB_URL, movieName));
        }

        private Movie ParseMovieFromHtmlStream(Stream htmlStream)
        {
            var doc = new HtmlDocument();

            doc.Load(htmlStream, Encoding.UTF8);

            var parser = new DobrakHtmlParser(doc.DocumentNode);

            return parser.ParseMovie();
        }
    }
}
